# -*- coding: utf-8 -*-
# @Date    : 2024/2/4
# @Author  : zouy
# @Email: 874112501@qq.com
"""https://www.geetest.com/adaptive-captcha-demo

运行报错找不到模块，请以模块方式运行：python -m main.某验.某验四代.某验四代-click
"""
import os
import re
import sys
import uuid
import time
from urllib.parse import urljoin
import random

import requests
import parsel
from loguru import logger
import execjs

from main.某验.某验四代.util import call_back_param, get_jsonp, download_img, get_points, DIR_PATH

ss = requests.session()

ss.headers = {
    "Accept": "*/*",
    # "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "accept-language": "zh-CN,zh;q=0.9",
    "referer": "https://www.geetest.com/adaptive-captcha",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
}

# 1. 请求验证码首页，获取link标签中的js网址
index_url = "https://www.geetest.com/adaptive-captcha-demo"
response = ss.get(index_url)
sel = parsel.Selector(response.text)
captcha_demo_link = sel.xpath('//link[contains(@href, "adaptive-captcha-demo.js")]/@href').get()
captcha_demo_url = urljoin(index_url, captcha_demo_link)
# https://www.geetest.com/_next/static/yGLsUSoSGNFNvVZFXHBOL/pages/adaptive-captcha-demo.js
logger.info(f'1.请求首页：{captcha_demo_url}')

# 2.请求第一步的js网址， 提取captchaId
headers = {'referer': 'https://www.geetest.com/adaptive-captcha-demo'}
response = ss.get(captcha_demo_url, headers=headers)
resp_text = response.text
captcha_id = re.search(r'captchaId:\s*"(.*?)",', resp_text).group(1)
logger.info(f'2.获取captchaId: {captcha_id}')  # 同平台captchaId固定：24f56dc13c40dc4a02fd0318567caef5

# 3. 请求获取验证码相关信息
challenge = str(uuid.uuid4())
params = {
    "callback": call_back_param(),
    "captcha_id": captcha_id,
    "challenge": challenge,
    "client_type": "web",
    "risk_type": "word",  # ai, slide
    "lang": "zh"
}
ss.headers.update({
    'referer': "https://www.geetest.com/",
    'host': "gcaptcha4.geetest.com"
})
load_url = "https://gcaptcha4.geetest.com/load"
response = ss.get(load_url, params=params)
resp_json = get_jsonp(response.text)
# print(resp_json)
json_data = resp_json['data']

load_lot_number = json_data['lot_number']  # '7a559190e40a45ff994a9cd26e54e6bb'
load_payload = json_data['payload']  # '_b-sD20eax9oEJvmoMxvFFW...'
load_process_token = json_data['process_token']  # '9aa7741f1afa76b8955a7490af2bbb7783514f8a772ceaf68caa5e604ad26867'
pow_detail = json_data['pow_detail']  # 'md5'
ques = json_data['ques']  # 'md5'

# 4 下载验证码图片 (https://static.geetest.com/captcha_v4/e70fbf1d77/slide/4b268eea89/2022-04-21T09/bg/dce83aec8b994d928f06519b0bad4946.png)
static_url = 'https://static.geetest.com/'
click_imgs_path = download_img('click-imgs.png', url=urljoin(static_url, json_data['imgs']))
ques_path = []
for idx, que in enumerate(ques, start=1):
    slice_path = download_img(f'que-{idx}.png', url=urljoin(static_url, que))
    ques_path.append(slice_path)

# 5.获取点选坐标
points = get_points(ques_path, click_imgs_path)
logger.info(f'识别坐标位置：{points}')
userresponse = [[round(x / 300 * 10000 - 100), round(y / 200 * 10000 - 100)] for x, y in
                points]  # [[4128, 7325], [4993, 2933]],
passtime = random.randint(1000, 1800) * len(ques_path)

logger.info(f'w加密提供的参数：{captcha_id, load_lot_number, passtime, pow_detail, userresponse}')
# 6. 提交参数进行验证

with open(os.path.join(DIR_PATH, 'w4.js'), 'r', encoding='utf-8') as f:
    js_code = f.read()
ctx = execjs.compile(js_code)
w = ctx.call('genClickW4', captcha_id, load_lot_number, passtime, pow_detail, userresponse)

# logger.info(f'w值：{w}')
params = {
    "callback": call_back_param(),
    "captcha_id": captcha_id,
    "client_type": "web",
    "lot_number": load_lot_number,
    "risk_type": "word",
    "payload": load_payload,
    "process_token": load_process_token,
    "payload_protocol": "1",
    "pt": "1",
    "w": w
}
time.sleep(1)
verify_url = "https://gcaptcha4.geetest.com/verify"
response = ss.get(verify_url, params=params)
resp_json = get_jsonp(response.text)

data = resp_json.get('data', {})
if data.get('result') == 'success':
    logger.success(f'成功：{resp_json.get("data", {}).get("seccode")}')
else:
    logger.warning(f'失败：{resp_json}')
"""
成功：{
    'captcha_id': '24f56dc13c40dc4a02fd0318567caef5', 
    'lot_number': 'c76c90aefa7b44de87f177a764a5113c',
    'pass_token': '2bc6decbefe8ce16072925d84982bf567a080b0aac8f3844ce7d17b09a0f1c12',
    'gen_time': '1707069410', 'captcha_output': 'PIzIftzdkAwSq5NJfqPJNSoBPDqY-q9Snq9CPM_tBqfFfL6PrllUrJ4r6ibHtwbHD_bwXyGv9U2VfKd_y3ztYLl9TPHWY6GsushzWOePfcDZ7ksINA6VCUjRrdaTPkzWHfFEu8cV1Iqk8pasdJXdc2AqWU3zTRLy__dfsue7pU2pu7oYnF7XBWREW0NJHHcXUyWmrOTIC1Z_TARwg14FGKjK9dq7Q2VyNbGthr5dlDgjNiKTNwbpqMh08SpLEkoQW162seLnROlsnTP4xQS_EiNxzi126JcrCTezImU_-mbdrCbPtfTKQN8YwjPKoYRzR8yVMKDJwa4vo18f4wlcNtE---bbQA5ZNAsnudDzqh0R11rMfJElf4h7Zkz08qdwLjcQwTsRJmDeuf5qjvurizGXyt9F3DbGqF6o6yqfFQw='
}
"""